package com.boang.service.impl;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.boang.config.ConditionalOnStorage;
import com.boang.entity.dto.StorageDO;
import com.boang.service.CloudStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author: 13813
 * @date: 2025/3/6 8:44
 */
@Service
@Slf4j
@ConditionalOnStorage(type = "aliyun")
public class AliyunOssServiceImpl implements CloudStorageService {

    private final OSS ossClient;
    private final String bucket;
    private final String endpoint;

    public AliyunOssServiceImpl(StorageDO properties) throws com.aliyuncs.exceptions.ClientException {
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        StorageDO.Aliyun config = properties.getAliyun();
        ossClient = OSSClientBuilder.create()
                .endpoint(config.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .region(config.getRegion())
                .build();
        this.bucket = config.getBucket();
        this.endpoint = config.getEndpoint();
    }

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            String objectName = file.getOriginalFilename();
            ossClient.putObject(bucket, objectName, inputStream);
            // 返回文件在OSS中的URL，这个URL需要根据实际情况生成
            // 例如：https://your-bucket-name.oss-cn-hangzhou.aliyuncs.com/your-file-name
            return "https://" + bucket + "." + this.endpoint + "/" + objectName;
        } catch (OSSException oe) {
            log.debug("Error Code:{}", oe.getErrorCode());
        } catch (ClientException | IOException ce) {
            log.debug("Error Message:{}", ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
